<template>
  <div class="container">
    <div class="app-container">
      <!-- 条件筛选 -->
      <el-card class="hr-block">
        <el-form label-width="120px">
          <el-form-item label="聘用形式:">
            <el-checkbox-group v-model="formData.approvalsTypeChecks">
              <el-checkbox v-for="item in approvalsType" :key="item.id" :label="item.id" @change="checkChange(item)">{{
              item.value }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <!-- <el-form-item label="员工状态:">
            <el-checkbox-group v-model="formData.approvalsStateChecks">
              <el-checkbox v-for="item in approvalsState" :key="item.id" :label="item.id" @change="">{{
              item.value }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item> -->
          <el-form-item label="部门:">
            <el-checkbox-group v-model="formData.departmentChecks">
              <el-checkbox v-for="item in departments" :key="item.id" :label="item.id" @change="checkChange(item)">{{
              item.name }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </el-card>
      <!-- 表单 -->

      <el-card class="hr-block">
        <el-table :data="list" style="width: 100%">
          <el-table-column type="index" label="序号" />
          <el-table-column prop="userName" label="姓名" />
          <el-table-column prop="mobile" label="手机" />
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column prop="formOfEmployment" width="100" label="聘用形式" />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" width="130" label="入职时间">
            <!-- <span>{{ list.timeOfEntry | formatDate }}</span> -->
          </el-table-column>
          <el-table-column prop="currentBasicSalary" label="工资基数" />
          <el-table-column label="提成工资" prop="currentPostWage" width="100"></el-table-column>
          <el-table-column label="操作" width="260">
            <template slot-scope="scope" style>
              <el-button v-if="scope.row.currentBasicSalary + scope.row.currentPostWage > 0" size="mini" type="primary"
                @click="changeSalary('ChangeSalary', scope.row.id)">调薪</el-button>
              <el-button v-else size="mini" type="danger"
                @click="fixedSalary('FixedSalary', scope.row.id)">定薪</el-button>
              <el-button type="text" size="mini">
                <router-link :to="{ 'path': '/salary/detail/' + scope.row.id }">查看</router-link>
                <!-- <router-link :to="{ 'path': '/salarys/details/' + yearMonth + '/' + scope.row.id }">查看</router-link> -->
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="center" style="height: 50px" align="middle">
          <el-pagination background layout="prev,pager,next" :total="page.total" :current-page="page.pageNum"
            :page-size="page.pageSize" @current-change="pageChange" />

        </el-row>
      </el-card>
      <!--查看弹框-->
      <el-dialog :title="topLabel" :visible.sync="centerDialogVisible" width="50%" left>
        <component :is="currentComponent" :user-salary="selectedSalaryInfo" :user-id="selectUserId"
          @onDialogCancel="centerDialogVisible = false" @res="handleUpdate" />
        <!-- <ChangeSalary  :user-salary="selectedSalaryInfo" :user-id="selectUserId" @onDialogCancel="centerDialogVisible=false" /> -->
        <!-- <FixedSalary  /> -->
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getDepartment } from '@/api/department'
import { getSalarys, getSalarysById } from '@/api/salary'
import ChangeSalary from './components/change-salary'
import FixedSalary from './components/fixed-salary'
import pageTools from './components/page-tools.vue'
export default {
  name: 'Salary',
  components: { ChangeSalary, pageTools, FixedSalary },
  data() {
    return {
      topLabel: '',
      selectUserId: null,
      currentComponent: '',
      centerDialogVisible: false,
      selectedSalaryInfo: {},
      formData: {
        approvalsTypeChecks: [], // 选择的聘用形式
        approvalsStateChecks: [], // 选择的员工状态
        departmentChecks: [], // 选择的部门
      },
      approvalsType: [
        { id: 1, value: '正式' },
        { id: 2, value: '非正式' },
      ],
      approvalsState: [
        { id: 1, value: '在职' },
        { id: 2, value: '离职' },
      ],
      departments: [],
      page: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      list: [],
      filteredList:[],
      yearMonth: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-01',

    };
  },
  created() {
    this.getList();
    this.getDepartment()
  },
  methods: {
    checkChange(item) {
      // 确定当前被点击的复选框是否被选中
      const jsonString = JSON.stringify(this.formData.approvalsTypeChecks);
      const jsonString2 = JSON.stringify(this.formData.departmentChecks);
      console.log(this.formData.approvalsTypeChecks);
      console.log(this.formData.departmentChecks);
      let approvalsTypeChecks = jsonString.split(',')
      let departmentChecks = jsonString2.split(',')
      approvalsTypeChecks = approvalsTypeChecks.map(item => {
        // 去除每个元素两边的空格，并去除可能的方括号
        return item.replace(/^\[|\]$/g, '');
      });
      departmentChecks = departmentChecks.map(item => {
        // 去除每个元素两边的空格，并去除可能的方括号
        return item.replace(/^\[|\]$/g, '');
      });
      this.list = this.filteredList
      this.list = this.list.filter(item => {
        if (jsonString.length === 2) {
          return true;
        }
        // console.log(item.formOfEmploymentId);
        // console.log(approvalsTypeChecks);
        // console.log(approvalsTypeChecks.includes(item.formOfEmploymentId));
        return approvalsTypeChecks.includes(item.formOfEmploymentId);
      });
      const list2=this.list
      this.list= list2.filter(item => {
        if (jsonString2.length === 2) {
          return true;
        }
        return departmentChecks.includes(item.departmentId);
      });
    },
    async getDepartment() {
      this.departments = await getDepartment()
    },
    handleUpdate(eventData) {
      // 处理从子组件传递过来的数据
      console.log(`res: ${eventData.res}`);
      const jsonString = JSON.stringify(eventData.res);
      // console.log(jsonString);
      this.list = JSON.parse(jsonString);
    },
    fixedSalary(key, userId) {
      console.log(key, userId)
      this.topLabel = '定薪'
      this.currentComponent = key
      this.centerDialogVisible = true
      this.selectUserId = userId
    },
    getList(data) {
      getSalarys(data).then(response => {
        // 请求成功，处理返回的数据
        console.log('获取薪资列表成功:', response);
        this.list = response.list;
        this.filteredList = response.list;
        this.page.total = response.total
      }).catch(error => {
        // 请求失败，处理错误
        console.error('获取薪资列表失败:', error);
      });
    },
    async changeSalary(key, userId) {
      this.topLabel = '调薪'
      this.currentComponent = key
      this.centerDialogVisible = true
      this.selectUserId = userId
      getSalarysById(userId).then(response => {
        // 请求成功，处理返回的数据
        console.log('获取薪资详情成功:', response);
        this.selectedSalaryInfo = response
      }).catch(error => {
        // 请求失败，处理错误
        console.error('获取薪资详情失败:', error);
      });
      // this.selectedSalaryInfo = await getSalaryDetail(userId)
    },
    pageChange(page) {
      // 页码改变时的回调
      console.log('当前页:', page)
      this.page.pageNum = page
      const params = {
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize
      };
      this.getList(params)
    },
  }
}
</script>
